﻿/// <summary>
/// Copyright(c) 2008-2009北京玖富时代投资顾问有限公司, All Rights Reserved.
/// 
/// 通用公共方法--杂项，例如数据格式验证
/// 
/// 版本：Ver 1.0
/// 作者：【周燕龙】
/// 时间：2009-09-08
/// </summary>

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Data;
using System.Collections;
using Hisuntech.SystemFramework.Exception;

namespace Hisuntech.SystemFramework.Common
{
    public class Utils
    {
        #region 格式验证

        /// <summary>
        /// 只能输入数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNumeric(string value)
        {
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^[+]?[0-9]*[.]?[0-9]*$");
            return re.IsMatch(value);
        }

        /// <summary>
        /// 保存小数点两位
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNumTwos(string value)
        {
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^(0?|[1-9]\d*)(\.\d{0,2})?$");
            return re.IsMatch(value);
        }

        /// <summary>
        /// 保存小数点几位
        /// </summary>
        /// <param name="value"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        public static bool IsNumTwos(string value, string num)
        {
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^(0?|[1-9]\d*)(\.\d{0," + num + "})?$");
            return re.IsMatch(value);
        }


        /// <summary>
        /// 判断是否数字/字母
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>布尔值</returns>
        public static bool IsNatural_Number(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 判断是否数字
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>布尔值</returns>
        public static bool IsNumber(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9]+$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 判断是否float
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>布尔值</returns>
        public static bool IsFloat(string str)
        {
            //System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^([1-9]\d*)|(([1-9]\d*)(\.\d{1,})|(0\.[1-9]\d*)|(0\.\d*[1-9]))$");
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[+-]?\d+(\.\d+)?$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 判断是否是手机号
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>布尔值</returns>
        public static bool IsTelephone(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^(1)\d{10}$"); //new System.Text.RegularExpressions.Regex(@"^(?:13\d|15[0189])-?\d{5}(\d{3}|\*{3})$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 判断是否是Email
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>布尔值</returns>
        public static bool IsEmail(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        /// 判断带有区号的电话号码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static bool isChinaPhone(string phone)
        {
            bool isOk = false;
            string strReg = @"^0\d{2,3}\-\d{7,8}$";
            System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(phone, strReg);
            if (match.Success)
            {
                isOk = true;
            }

            return isOk;
        }

        /// <summary>
        /// 安全的转换 double 数字
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double ConvertMyDouble(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return 0;
            string str = obj.ToString();
            if (string.IsNullOrEmpty(str))
                return 0;
            return Convert.ToDouble(str);
        }

        /// <summary>
        /// 判断TextBox的值是否为空
        /// </summary>
        /// <param name="tb1">TextBox</param>
        /// <param name="name">TextBox的含义</param>
        /// <returns>布尔值</returns>
        public static bool IsNull(TextBox tb1, string name)
        {
            bool b = true;
            if (tb1.Text.Trim() == "")
            {
                b = false;

                MessageWrap.ShowWarning(name + "不能为空!");
                //Message.Show(name + "不能为空!");
                tb1.Focus();
            }
            return b;
        }

        public static bool IsNull(RichTextBox tb1, string name)
        {
            bool b = true;
            if (tb1.Text.Trim() == "")
            {
                b = false;
                MessageWrap.ShowInformation(name + "不能为空!");
                tb1.Focus();
            }
            return b;
        }
        
        #endregion

        #region 过滤

        /// <summary>
        /// 将TextBox的值取出数字
        /// </summary>
        /// <param name="textBox1">TextBox</param>
        public static void setControlNumber(TextBox textBox1)
        {
            if (textBox1.Text.Length > 0 && textBox1.Text.Substring(textBox1.Text.Length - 1, 1) == ".")
                return;
            if (IsNumber(textBox1.Text) || IsFloat(textBox1.Text))
            {//数字   
                // getLot();
            }
            else
            {
                if (textBox1.Text.Length > 0)
                {
                    textBox1.Text = getNumber(textBox1.Text);
                }
            }
            textBox1.SelectionStart = textBox1.Text.Length;
        }

        /// <summary>
        /// 过滤非数字的字符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>数字</returns>
        public static string getNumber(string str)
        {
            string returnstr = "";
            str = str.Replace("１", "1").Replace("２", "2").Replace("３", "3").Replace("４", "4").Replace("５", "5").Replace("６", "6").Replace("７", "7").Replace("８", "8").Replace("９", "9").Replace("０", "0").Replace("。", ".");
            for (int i = 0; i < str.Length; i++)
            {
                if (IsNumber(str.Substring(i, 1)) || str.Substring(i, 1) == ".")
                {
                    returnstr += str.Substring(i, 1);
                }
            }
            return returnstr;
        }


        /// <summary> 
        /// 去除HTML标记 
        /// </summary> 
        /// <param name="Htmlstring">包括HTML的源码 </param> 
        /// <returns>已经去除后的文字</returns> 
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本 
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML 
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Htmlstring.Replace(@"&ldquo;", "");
            Htmlstring = Htmlstring.Replace(@"&rdquo;", "");
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            return Htmlstring;
        }
        public static string NoHTML(string Htmlstring, string type)
        {
            //删除脚本 
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML 
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            if (type != "")
                Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            //else
            //    Htmlstring = Htmlstring.Replace("", "");
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Htmlstring.Replace(@"&ldquo;", "");
            Htmlstring = Htmlstring.Replace(@"&rdquo;", "");
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            return Htmlstring;
        }

        /// <summary>
        /// 清除html标签
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public static string ClearHTML(string Htmlstring)
        {
            return System.Text.RegularExpressions.Regex.Replace(Htmlstring, "<[^>]+>", "").Replace("\r\n", "").Replace("&nbsp;", "");
 
        }

        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="Temp">字符串</param>
        /// <returns>过滤特殊字符后的值</returns>
        public static string StringReplaceDangerCode(string Temp)
        {
            Temp = Temp.Trim();
            Temp = Temp.Replace("'", "");
            Temp = Temp.Replace("\"", "");
            Temp = Temp.Replace("or", "");
            Temp = Temp.Replace("&", "");
            Temp = Temp.Replace("*", "");
            Temp = Temp.Replace("select ", "");
            Temp = Temp.Replace("insert ", "");
            Temp = Temp.Replace("delete ", "");
            Temp = Temp.Replace("count(", "");
            Temp = Temp.Replace("drop table ", "");
            Temp = Temp.Replace("update ", "");
            Temp = Temp.Replace("truncate ", "");
            Temp = Temp.Replace("asc(", "");
            Temp = Temp.Replace("mid(", "");
            Temp = Temp.Replace("char(", "");
            Temp = Temp.Replace("xp_cmdshell", "");
            Temp = Temp.Replace("exec master", "");
            Temp = Temp.Replace("net localgroup administrators", "");
            Temp = Temp.Replace(" and ", "");
            Temp = Temp.Replace("net user", "");
            Temp = Temp.Replace(" or ", "");
            Temp = Temp.Replace("　", "");
            return Temp;
        }
        
        #endregion

        #region 控件操作相关

        /// <summary>
        /// 取得RadioButton的值
        /// </summary>
        /// <param name="ctl">RadioButton</param>
        /// <param name="tagOrtext">tag或者text</param>
        /// <returns>RadioButton的值</returns>
        public static string getRadioButton(Control ctl, string tagOrtext)
        {
            string str = "";
            foreach (Control ctl_Listctl in ctl.Controls)
            {
                if (ctl_Listctl is RadioButton)
                {
                    if (((RadioButton)ctl_Listctl).Checked)
                    {
                        if (tagOrtext == "tag")
                        {
                            str = ((RadioButton)ctl_Listctl).Tag.ToString();
                        }
                        else
                        {
                            str = ((RadioButton)ctl_Listctl).Text;
                        }
                    }
                }
            }
            return str;
        }

        /// <summary>
        /// 给RadioButton赋值
        /// </summary>
        /// <param name="value">要赋的值</param>
        /// <param name="ctl">RadioButton</param>
        /// <param name="tagOrtext">tag或者text</param>
        public static void selRadioButton(string value, Control ctl, string tagOrtext)
        {
            foreach (Control ctl_Listctl in ctl.Controls)
            {
                if (ctl_Listctl is RadioButton)
                {
                    if (tagOrtext == "tag")
                    {
                        if (((RadioButton)ctl_Listctl).Tag.ToString() == value)
                        {
                            ((RadioButton)ctl_Listctl).Checked = true;
                        }
                    }
                    else
                    {
                        if (((RadioButton)ctl_Listctl).Text == value)
                        {
                            ((RadioButton)ctl_Listctl).Checked = true;
                        }
                    }

                }
            }
        }

        


        /// <summary>
        /// 为顶部图片增加文字 dth 2009.2.24
        /// </summary>
        /// <param name="picBoxHead"></param>
        /// <param name="text"></param>
        public static void WriteHeadPicText(PictureBox picBoxHead, string text)
        {
            Graphics Gra = Graphics.FromImage(picBoxHead.Image);
            Font _F = new Font("黑体", 23F, FontStyle.Bold);
            SolidBrush _B = new SolidBrush(Color.White);
            Pen _P = new Pen(_B, 10);
            Gra.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Gra.DrawString(text, _F, _B, 98, 70);
            Gra.Dispose();
        }

        public static void WriteHeadPicText(PictureBox picBoxHead, string text, float Size)
        {
            if (Size == 0)
            {
                Size = 23F;
            }
            Graphics Gra = Graphics.FromImage(picBoxHead.Image);
            Font _F = new Font("黑体", Size, FontStyle.Bold);
            SolidBrush _B = new SolidBrush(Color.White);
            Pen _P = new Pen(_B, 10);
            Gra.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Gra.DrawString(text, _F, _B, 98, 70);
            Gra.Dispose();
        }


        #region 设置RichTextBox行距

        /// <summary>
        /// 设置RichTextBox行距
        /// </summary>
        /// <param name="rtb">RichTextBox控件</param>
        public static void SetLineSpaceProperty(RichTextBox rtb)
        {
            rtb.ReadOnly = true;
            rtb.IsAccessible = false;
            PARAFORMAT2 fmt = new PARAFORMAT2();
            fmt.cbSize = Marshal.SizeOf(fmt);
            fmt.bLineSpacingRule = 4;
            fmt.dyLineSpacing = 270;//20 * (10 + 3);//((int)richTextBox1.Font.Size) * 20 * ((int)ud.Value);
            fmt.dwMask = WindowMsg.PFM_LINESPACING;
            try
            {
                WinAPI.SendMessage(rtb.Handle, WindowMsg.EM_SETPARAFORMAT, 0, ref fmt);
            }
            catch (System.Exception ex)
            {
                ExceptionHandler.HandleException(ex);
            }
        }

        /// <summary>
        /// 设置RichTextBox行距
        /// </summary>
        /// <param name="ctl">控件</param>
        /// <param name="dyLineSpacing">间距</param>
        public static void SetLineSpaceProperty(Control ctl, int dyLineSpacing)
        {
            PARAFORMAT2 fmt = new PARAFORMAT2();
            fmt.cbSize = Marshal.SizeOf(fmt);
            fmt.bLineSpacingRule = 4;// bLineSpacingRule;
            fmt.dyLineSpacing = dyLineSpacing;
            fmt.dwMask = WindowMsg.PFM_LINESPACING;
            try
            {
                WinAPI.SendMessage(ctl.Handle, WindowMsg.EM_SETPARAFORMAT, 0, ref fmt);
            }
            catch (System.Exception ex)
            {
                ExceptionHandler.HandleException(ex);
            }
        }

        /// <summary>
        /// 设置RichTextBox选中字体颜色
        /// </summary>
        /// <param name="rtb">RichTextBox控件</param>
        /// <param name="start_tindex">开始索引</param>
        /// <param name="length">选择长度</param>
        /// <param name="color">要设置的颜色</param>
        public static void setRichTextSelectionColor(RichTextBox rtb, int start_tindex, int length, Color color)
        {
            rtb.SelectionStart = start_tindex;
            rtb.SelectionLength = length;
            rtb.SelectionColor = color;
        }

        #endregion


        /// <summary>
        /// 获取文本框行数
        /// </summary>
        /// <param name="ctl">控制</param>
        /// <returns>行数</returns>
        public static int GetLineCount(Control ctl)
        {
            int linecount = 0;
            try
            {
                linecount = WinAPI.SendMessage(ctl.Handle, WindowMsg.EM_GETLINECOUNT, 0, 0);
            }
            catch
            {
                linecount = 0;
            }
            return linecount;
        }

        #endregion

        #region Excle 相关
        /// <summary>
        /// 将图片插入到Excel
        /// </summary>
        /// <param name="RangeName">单元格名称</param>
        /// <param name="PicturePath">图片的绝对路径</param>
        /// <param name="PictuteWidth">图片在Excel中显示的宽度</param>
        /// <param name="PictureHeight">图片在Excel中显示的高度</param>
        public void InsertPicture(string RangeName, string PicturePath, float PictuteWidth, float PictureHeight)
        {
            Microsoft.Office.Interop.Excel.Range m_objRange = null;
            Microsoft.Office.Interop.Excel._Worksheet m_objSheet = null;
            object m_objOpt = System.Reflection.Missing.Value;

            m_objRange = m_objSheet.get_Range(RangeName, m_objOpt);
            m_objRange.Select(); float PicLeft, PicTop;
            PicLeft = Convert.ToSingle(m_objRange.Left);
            PicTop = Convert.ToSingle(m_objRange.Top);
            m_objSheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, PictuteWidth, PictureHeight);
        }
        /// <summary>
        /// 导出EXECL(基金比较)报表
        /// </summary>
        /// <param name="excelTableList"></param>
        /// <param name="FileName"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool SaveDataTableToExcel3(List<List<DataTable>> excelTableList, string[] FileName, string filePath, Hashtable htlist, string s)
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
                try
                {
                    app.Visible = true;
                    Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true);
                    int w1 = 0;
                    for (int w = 0; w < FileName.Length; w++)
                    {
                        Microsoft.Office.Interop.Excel.Worksheet wSheet = null;
                        if (w == 0)
                        {
                            wSheet = wBook.Worksheets[w + 1] as Microsoft.Office.Interop.Excel.Worksheet;
                            wSheet.Name = FileName[w];
                        }
                        else
                        {
                            Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)wBook.
                            Worksheets.Add(Type.Missing, wBook.ActiveSheet, Type.Missing, Type.Missing);
                            xlSheet.Name = FileName[w];
                            wSheet = wBook.Worksheets[w + 1] as Microsoft.Office.Interop.Excel.Worksheet;
                        }
                        string p = "";
                        if (htlist.Count != 0)
                        {
                            p = htlist[FileName[w].ToString()].ToString();

                        }
                        if (p != "")
                        {
                            Microsoft.Office.Interop.Excel.Range m_objRange = null;
                            object m_objOpt = System.Reflection.Missing.Value;
                            if (wSheet.Name == "走势比较")
                            {

                                wSheet.Cells[1, 1] = "走势比较" + s + "走势图";
                            }

                            if (wSheet.Name == "投资组合")
                            {
                                //string s2 = "投资组合";
                                //wSheet.Cells[1, 1] = s2;
                                int zrow = 0;
                                for (int l = 0; l < excelTableList[w1].Count; l++)
                                {
                                    DataTable excelTable = excelTableList[w1][l];
                                    if (l != 0)
                                        zrow += 2;

                                    if (l == 0)
                                    {
                                        string mingxi = excelTable.TableName;
                                        wSheet.Cells[1, 1] = mingxi;
                                    }
                                    else if (l == 1)
                                    {
                                        string mingxi = excelTable.TableName;
                                        wSheet.Cells[zrow + 2, 1] = mingxi;
                                    }
                                    else if (l == 2)
                                    {
                                        string mingxi = excelTable.TableName;
                                        wSheet.Cells[zrow + 2, 1] = mingxi;
                                    }

                                    if (excelTable.Rows.Count > 0)
                                    {
                                        int row = 0;
                                        row = excelTable.Rows.Count;
                                        int col = excelTable.Columns.Count;
                                        for (int n = 0; n < row; n++)
                                        {
                                            zrow += 1;
                                            for (int j = 0; j < col; j++)
                                            {
                                                try
                                                {
                                                    string str = Convert.ToString(excelTable.Rows[n][j]);
                                                    wSheet.Cells[zrow + 2, j + 1] = str;
                                                }
                                                catch (System.Exception e)
                                                {
                                                    return false;
                                                }
                                            }
                                        }
                                    }
                                    int size = excelTable.Columns.Count;
                                }
                                w1++;
                            }
                            m_objRange = wSheet.get_Range("C3", m_objOpt);
                            wSheet.Shapes.AddPicture(p, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 10, 100, 500, 500);

                        }
                        else
                        {
                            int zrow = 0;

                            for (int l = 0; l < excelTableList[w1].Count; l++)
                            {
                                DataTable excelTable = excelTableList[w1][l];
                                if (l != 0)
                                    zrow += 2;

                                if (l == 0)
                                {
                                    string mingxi = excelTable.TableName;
                                    wSheet.Cells[1, 1] = mingxi;
                                }
                                else if (l == 1)
                                {
                                    string mingxi = excelTable.TableName;
                                    wSheet.Cells[zrow + 2, 1] = mingxi;
                                }
                                else if (l == 2)
                                {
                                    string mingxi = excelTable.TableName;
                                    wSheet.Cells[zrow + 2, 1] = mingxi;
                                }

                                if (excelTable.Rows.Count > 0)
                                {
                                    int row = 0;
                                    row = excelTable.Rows.Count;
                                    int col = excelTable.Columns.Count;
                                    for (int n = 0; n < row; n++)
                                    {
                                        zrow += 1;
                                        for (int j = 0; j < col; j++)
                                        {
                                            try
                                            {
                                                string str = Convert.ToString(excelTable.Rows[n][j]);
                                                wSheet.Cells[zrow + 2, j + 1] = str;
                                            }
                                            catch (System.Exception e)
                                            {
                                                return false;
                                            }
                                        }
                                    }
                                }
                                int size = excelTable.Columns.Count;
                            }
                            w1++;
                        }
                    }

                    //设置禁止弹出保存和覆盖的询问提示框 
                    app.DisplayAlerts = false;
                    app.AlertBeforeOverwriting = false;
                    //保存工作簿 
                    wBook.SaveAs(filePath,
                        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
                                    Missing.Value, Missing.Value);
                    ////保存excel文件 
                    app.Workbooks.Close();
                    app.Quit(); //这一句是非常重要的，否则Excel对象不能从内存中退出 
                    app = null;
                    return true;
                }

                catch (System.Exception err)
                {
                    return false;
                }
                finally
                {

                }

            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }
            return false;
        }

        /// <summary>
        /// 导出EXECL(FOF)报表
        /// </summary>
        /// <param name="excelTable">要导出的数据</param>
        /// <param name="FileName">sheet名称</param>
        /// <param name="filePath">保存路径</param>
        /// <returns>是否成功</returns>
        public static bool SaveDataTableToExcel2(List<List<DataTable>> excelTableList, string[] FileName, string filePath, List<Hashtable> htlist)
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
                try
                {
                    app.Visible = true;
                    Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true);
                    int w1 = 0;
                    for (int w = 0; w < FileName.Length; w++)
                    {
                        Microsoft.Office.Interop.Excel.Worksheet wSheet = null;
                        if (w == 0)
                        {
                            wSheet = wBook.Worksheets[w + 1] as Microsoft.Office.Interop.Excel.Worksheet;
                            wSheet.Name = FileName[w];
                        }
                        else
                        {
                            Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)wBook.
                            Worksheets.Add(Type.Missing, wBook.ActiveSheet, Type.Missing, Type.Missing);
                            xlSheet.Name = FileName[w];
                            wSheet = wBook.Worksheets[w + 1] as Microsoft.Office.Interop.Excel.Worksheet;
                        }

                        int zrow = 0;
                        for (int l = 0; l < excelTableList[w].Count; l++)
                        {
                            DataTable excelTable = excelTableList[w][l];
                            if (l != 0)
                                zrow += 2;

                            if (l == 0)
                            {
                                string mingxi = "FOF组合明细";
                                wSheet.Cells[1, 1] = mingxi;

                            }
                            else if (l == 1)
                            {
                                string mingxi = "基金收益";
                                wSheet.Cells[zrow + 2, 1] = mingxi; ;
                            }
                            else if (l == 2)
                            {
                                string mingxi = "基金评级";
                                wSheet.Cells[zrow + 2, 1] = mingxi; ;
                            }
                            else if (l == 3)
                            {
                                string mingxi = "历史FOF";
                                wSheet.Cells[zrow + 2, 1] = mingxi; ;
                            }

                            if (excelTable.Rows.Count > 0)
                            {
                                int row = 0;
                                row = excelTable.Rows.Count;
                                int col = excelTable.Columns.Count;
                                for (int n = 0; n < row; n++)
                                {
                                    zrow += 1;
                                    for (int j = 0; j < col; j++)
                                    {
                                        try
                                        {
                                            string str = Convert.ToString(excelTable.Rows[n][j]);
                                            if (j == 0)
                                            {
                                                str = "'" + str;
                                            }
                                            wSheet.Cells[zrow + 2, j + 1] = str;
                                        }
                                        catch (System.Exception e)
                                        {
                                            return false;
                                        }
                                    }
                                }
                            }
                            int size = excelTable.Columns.Count;

                        }

                        string p = "";
                        string p1 = "";
                        if (htlist.Count != 0)
                        {

                            p = htlist[w][FileName[w].ToString()].ToString();
                            p1 = htlist[w]["全部收益"].ToString();
                        }
                        if (p != "" && p1 != "")
                        {
                            Microsoft.Office.Interop.Excel.Range m_objRange = null;
                            object m_objOpt = System.Reflection.Missing.Value;
                            m_objRange = wSheet.get_Range("C250", m_objOpt);
                            wSheet.Shapes.AddPicture(p, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 10, zrow * 17, 200, 150);
                            m_objRange = wSheet.get_Range("C250", m_objOpt);
                            wSheet.Shapes.AddPicture(p1, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 250, zrow * 17, 200, 150);
                        }
                    }
                    //设置禁止弹出保存和覆盖的询问提示框 
                    app.DisplayAlerts = false;
                    app.AlertBeforeOverwriting = false;
                    //保存工作簿 
                    wBook.SaveAs(filePath,
                        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
                                    Missing.Value, Missing.Value);
                    ////保存excel文件 
                    app.Workbooks.Close();
                    app.Quit(); //这一句是非常重要的，否则Excel对象不能从内存中退出 
                    app = null;
                    return true;

                }

                catch (System.Exception err)
                {
                    return false;
                }

                finally
                {

                }

            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }
            return false;
        }

        /// <summary>
        /// 导出EXECL报表备份
        /// </summary>
        /// <param name="excelTable">要导出的数据</param>
        /// <param name="FileName">sheet名称</param>
        /// <param name="filePath">保存路径</param>
        /// <returns>是否成功</returns>
        public static bool SaveDataTableToExcel(ArrayList excelTable, string[] FileName, string filePath)
        {
            try
            {
                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
                try
                {
                    app.Visible = false;
                    Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true);
                    for (int i = 0; i < excelTable.Count; i++)
                    {
                        Microsoft.Office.Interop.Excel.Worksheet wSheet = null;
                        if (i == 0)
                        {
                            wSheet = wBook.Worksheets[i + 1] as Microsoft.Office.Interop.Excel.Worksheet;
                            wSheet.Name = FileName[i];
                        }
                        else
                        {
                            Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)wBook.
                            Worksheets.Add(Type.Missing, wBook.ActiveSheet, Type.Missing, Type.Missing);
                            xlSheet.Name = FileName[i];
                            wSheet = wBook.Worksheets[i + 1] as Microsoft.Office.Interop.Excel.Worksheet;
                        }

                        if (((DataTable)excelTable[i]).Rows.Count > 0)
                        {
                            int row = 0;
                            row = ((DataTable)excelTable[i]).Rows.Count;
                            int col = ((DataTable)excelTable[i]).Columns.Count;
                            for (int n = 0; n < row; n++)
                            {
                                for (int j = 0; j < col; j++)
                                {
                                    string str = ((DataTable)excelTable[i]).Rows[n][j].ToString();
                                    wSheet.Cells[n + 2, j + 1] = str;
                                }
                            }
                        }
                        int size = ((DataTable)excelTable[i]).Columns.Count;
                    }

                    //设置禁止弹出保存和覆盖的询问提示框 
                    app.DisplayAlerts = false;
                    app.AlertBeforeOverwriting = false;
                    //保存工作簿 
                    wBook.SaveAs(filePath,
                        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
                                    Missing.Value, Missing.Value);
                    ////保存excel文件 
                    app.Workbooks.Close();
                    app.Quit(); //这一句是非常重要的，否则Excel对象不能从内存中退出 
                    app = null;
                    return true;
                }

                catch (System.Exception err)
                {
                    return false;
                }

                finally
                {

                }

            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }
            return false;
        }

        #endregion

        #region 生成图片

        /// <summary>
        /// 生成Panel 控件图片
        /// </summary>
        /// <param name="panel1">panel 控件(自动保存panel控件上所有控件生成到图片对像里)</param>
        /// <returns>返回生成图片保存的图片路径</returns>
        public static string ChartFileImage(System.Windows.Forms.Panel panel1)
        {
            string FileImageUrl = "";
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\ChartImage"))
            {
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\ChartImage");
            }
            FileImageUrl = Application.StartupPath + "\\ChartImage\\9fbankChart" + DateTime.Now.ToFileTime() + System.Guid.NewGuid().ToString() + ".png";
            //Bitmap bitGraph = new Bitmap(panel1.Width, panel1.Height);
            //Rectangle nRectangle = new Rectangle(0, 0, panel1.Width, panel1.Height);
            //panel1.DrawToBitmap(bitGraph, nRectangle);
            //Graphics g1 = Graphics.FromImage(bitGraph);
            //IntPtr hdcBitmap = g1.GetHdc();
            Bitmap bitGraph = null;
            if (panel1.BackgroundImage == null)
                bitGraph = new Bitmap(panel1.Width, panel1.Height);
            else
                bitGraph = new Bitmap(panel1.BackgroundImage, panel1.Width, panel1.Height);



            for (int i = panel1.Controls.Count - 1; i >= 0; i--)
            {
                Control ctl = panel1.Controls[i];
                if (ctl.Visible == false) continue;
                Rectangle cRect = new Rectangle(ctl.Location.X, ctl.Location.Y, ctl.Width, ctl.Height);
                ctl.DrawToBitmap(bitGraph, cRect);
                if (ctl.HasChildren)
                {
                    for (int j = ctl.Controls.Count - 1; j >= 0; j--)
                    {
                        Control ctl1 = ctl.Controls[j];
                        if (ctl1.Visible == false) continue;
                        Rectangle cRect1 = new Rectangle(ctl1.Location.X + ctl.Location.X, ctl1.Location.Y + ctl.Location.Y, ctl1.Width, ctl1.Height);
                        ctl1.DrawToBitmap(bitGraph, cRect1);
                    }

                }
            }

            bitGraph.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Png);
            bitGraph.Dispose();
            return FileImageUrl;
        }


        /// <summary>
        /// 生成Chart控件图片
        /// </summary>
        /// <param name="chart1">chart控件</param>
        /// <returns>返回生成图片保存的图片路径</returns>
        public static string ChartFileImage(dotnetCHARTING.WinForms.Chart chart1)
        {
            string FileImageUrl = "";
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\ChartImage"))
            {
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\ChartImage");
            }

            System.Drawing.Image img = chart1.GetChartBitmap();
            FileImageUrl = Application.StartupPath + "\\ChartImage\\9fbankChart" + DateTime.Now.ToFileTime() + System.Guid.NewGuid().ToString() + ".jpg";
            img.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.Dispose();
            return FileImageUrl;
        }


        /// <summary>
        /// 生成ZedGraph控件图片
        /// </summary>
        /// <param name="zeds">ZedGraph控件</param>
        /// <returns>返回生成图片保存的图片路径</returns>
        public static string ChartFileImage(ZedGraph.ZedGraphControl zeds)
        {
            string FileImageUrl = "";
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\ChartImage"))
            {
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\ChartImage");
            }
            System.Drawing.Image img = zeds.GetImage();
            FileImageUrl = Application.StartupPath + "\\ChartImage\\9fbankChart" + DateTime.Now.ToFileTime() + System.Guid.NewGuid().ToString() + ".jpg";
            img.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.Dispose();
            return FileImageUrl;
        }

        /// <summary>
        /// 生成Panel 控件图片
        /// </summary>
        /// <param name="panel1">panel 控件(自动保存panel控件上所有控件生成到图片对像里)</param>
        /// <returns>返回生成图片保存的图片路径</returns>
        public static string ChartFileImage2(System.Windows.Forms.Panel panel1)
        {
            string FileImageUrl = "";
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\ChartImage"))
            {
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\ChartImage");
            }
            Random ran = new Random();
            int no = ran.Next(0, 1000);
            FileImageUrl = Application.StartupPath + "\\ChartImage\\9fbankChart" + no.ToString() + DateTime.Now.ToFileTime() + System.Guid.NewGuid().ToString() + ".png";
            Bitmap bitGraph = new Bitmap(panel1.Width, panel1.Height);
            foreach (Control ctl in panel1.Controls)
            {
                Rectangle nRectangle = new Rectangle(ctl.Location.X, ctl.Location.Y, ctl.Width, ctl.Height);
                ctl.DrawToBitmap(bitGraph, nRectangle);
            }
            Image myThumbnail = Utils.GetThumbImage(750, 523, bitGraph);
            //bitGraph.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Png);
            myThumbnail.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Png);
            bitGraph.Dispose();
            myThumbnail.Dispose();
            return FileImageUrl;

        }

        #region 缩略图

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="chart1">图片</param>
        /// <returns>图片地址</returns>
        public static string GetThumbImage(int width, int height, dotnetCHARTING.WinForms.Chart chart1)
        {

            string FileImageUrl = "";
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\ChartImage"))
            {
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\ChartImage");
            }

            System.Drawing.Image img = chart1.GetChartBitmap();
            FileImageUrl = Application.StartupPath + "\\ChartImage\\9fbankChart" + DateTime.Now.ToFileTime() + System.Guid.NewGuid().ToString() + ".jpg";
            Image myThumbnail = GetThumbImage(width, height, img);
            //bitGraph.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Png);
            myThumbnail.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.Dispose();
            myThumbnail.Dispose();
            return FileImageUrl;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="chart1">图片</param>
        /// <returns>图片地址</returns>
        public static string GetThumbImage(int width, int height, string imgPath)
        {

            string FileImageUrl = "";
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\ChartImage"))
            {
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\ChartImage");
            }

            System.Drawing.Image img = Image.FromFile(imgPath);
            FileImageUrl = Application.StartupPath + "\\ChartImage\\9fbankChart" +  DateTime.Now.ToFileTime() + System.Guid.NewGuid().ToString() + ".jpg";
            Image myThumbnail = GetThumbImage(width, height, img);
            //bitGraph.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Png);
            myThumbnail.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.Dispose();
            myThumbnail.Dispose();
            return FileImageUrl;
        }

        public static Image GetThumbImage(int width, int height, Image bitGraph)
        {
            Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            Image myThumbnail = bitGraph.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);
            return myThumbnail;
        }

        private static bool ThumbnailCallback()
        {
            return false;
        }


        #endregion

        #region 暂时没用
        /// <summary>
        /// 生成Panel(带滚动条) 控件图片
        /// </summary>
        /// <param name="Obj">panel 控件(自动保存panel控件上所有控件生成到图片对像里)</param>
        /// <returns>返回生成图片保存的图片路径</returns>
        public static string DrawMeToBitmap(Control Obj)
        {
            string FileImageUrl = "";
            if (!System.IO.Directory.Exists(Application.StartupPath + "\\ChartImage"))
            {
                System.IO.Directory.CreateDirectory(Application.StartupPath + "\\ChartImage");
            }
            Random ran = new Random();
            int no = ran.Next(0, 1000);
            FileImageUrl = Application.StartupPath + "\\ChartImage\\9fbankChart" + no.ToString() + DateTime.Now.ToFileTime() + System.Guid.NewGuid().ToString() + ".png";

            Bitmap bmp = new Bitmap(Obj.DisplayRectangle.Width, Obj.DisplayRectangle.Height);
            Graphics g = Graphics.FromImage(bmp);

            using (Brush backColorBrush = new SolidBrush(Obj.BackColor))
            {
                g.FillRectangle(backColorBrush, new Rectangle(0, 0, bmp.Width, bmp.Height));
                foreach (Control var in Obj.Controls)
                {
                    if (var.Height == 0) continue;
                    using (Bitmap b = new Bitmap(var.Width, var.Height))
                    {
                        var.DrawToBitmap(b, var.ClientRectangle);
                        g.DrawImage(b, var.Location.X, var.Location.Y + ((Panel)Obj).VerticalScroll.Value);
                    }
                }
            }
            bmp.Save(FileImageUrl, System.Drawing.Imaging.ImageFormat.Png);
            bmp.Dispose();
            return FileImageUrl;
        }
        
        #endregion   




        #endregion

        #region 其他

        public static string GetSubString(string val, int len)
        {
            if (string.IsNullOrEmpty(val))
                return "&nbsp;";
            else
            {
                if (val.Length > len)
                    return val.Substring(0, len) + "…";
                else
                    return val;
            }

        }

        /// <summary>
        /// 生成最新update副本文件updatecopy.exe by 邓仁建
        /// </summary>
        /// 
        public static void CreateCopyUpdate()
        {
            if (File.Exists(Application.StartupPath + "\\update.exe"))
            {
                string updatecopy = Application.StartupPath + "\\updatecopy.exe";
                FileInfo fi = new FileInfo(updatecopy);
                if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                {
                    fi.Attributes = FileAttributes.Normal;
                }
                File.Delete(updatecopy);

                File.Copy(Application.StartupPath + "\\update.exe", updatecopy, true);
            }
        }


        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="data">要序列化的对象</param>
        /// <returns>返回存放序列化后的数据缓冲区</returns>
        public static byte[] Serialize(object data)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream rems = new MemoryStream();
            formatter.Serialize(rems, data);
            return rems.GetBuffer();
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="data">数据缓冲区</param>
        /// <returns>对象</returns>
        public static object Deserialize(byte[] data)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream rems = new MemoryStream(data);
            data = null;
            return formatter.Deserialize(rems);
        }

        public static string getMd5(string str)
        {
            return (System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5"));
        }



        const string KEY_64 = "hcljiami";
        const string IV_64 = "HCLJIAMI"; //注意了，是8个字符，64位 

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">字符串</param>
        /// <returns>加密后的值</returns>
        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data">字符串</param>
        /// <returns>解密后的值</returns>
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// 设置字体
        /// </summary>
        /// <param name="ctl"></param>
        /// <returns></returns>
        public static Font GetCtlFont(Control ctl)
        {
            return new Font(ctl.Font.FontFamily, (int)(10 * config.h_Proportion));
        }

        /// <summary>
        ///  设置字体
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static Font GetCtlFont(Control ctl, float size)
        {
            return new Font(ctl.Font.FontFamily, (int)(size * config.h_Proportion));
        }

        public static string imagePath = Application.StartupPath + @"\ReSourceImage\";
        public enum ImageTypes { ImageLocation, BackgroundImage, Image, InitialImage };
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p_control">控件</param>
        /// <param name="p_type">图片引用类型</param>
        /// <param name="p_imgName">图片名称</param>
        public static void SetControlImage(Control p_control, ImageTypes p_type, string p_imgName)
        {
            string tempPath = imagePath + p_imgName;
            if (File.Exists(tempPath))
            {
                if (p_control is PictureBox)
                {
                    if (p_type == ImageTypes.ImageLocation)
                        ((PictureBox)p_control).ImageLocation = tempPath;
                    else if (p_type == ImageTypes.BackgroundImage)
                    {
                        ((PictureBox)p_control).BackgroundImage = GetImage(tempPath);
                        ((PictureBox)p_control).BackgroundImageLayout = ImageLayout.Stretch;

                    }
                    else if (p_type == ImageTypes.Image)
                        ((PictureBox)p_control).Image = GetImage(tempPath);
                }
                else if (p_control is Panel)
                {
                    ((Panel)p_control).BackgroundImage = GetImage(tempPath);
                    ((Panel)p_control).BackgroundImageLayout = ImageLayout.Stretch;

                }
                else if (p_control is Label)
                {
                    ((Label)p_control).Image = GetImage(tempPath);
                }
                else if (p_control is DevComponents.DotNetBar.LabelX)
                {
                    ((DevComponents.DotNetBar.LabelX)p_control).BackgroundImage = GetImage(tempPath);
                }
                else if (p_control is Button)
                {
                    if (p_type == ImageTypes.BackgroundImage)
                    {
                        ((Button)p_control).BackgroundImage = GetImage(tempPath);
                        ((Button)p_control).BackgroundImageLayout = ImageLayout.Stretch;
                        ((Button)p_control).FlatStyle = FlatStyle.Flat;
                    }

                    else if (p_type == ImageTypes.Image)
                        ((Button)p_control).Image = GetImage(tempPath);
                    else
                        ((Button)p_control).Image = GetImage(tempPath);
                }
                else if (p_control is Form)
                {
                    ((Form)p_control).BackgroundImage = GetImage(tempPath);
                }

            }

        }

        public static Image GetImage(string p_path)
        {
            return Image.FromFile(p_path);
        }
        public static Image GetImageByName(string p_path)
        {
            return Image.FromFile(imagePath + p_path);
        }

        #region 验证身份证的合法性
        /// <summary>
        /// 验证身份证的合法性
        /// </summary>
        /// <param name="Id">要验证的身份证号码,15或18位</param>
        /// <returns></returns>
        public static bool CheckIDCard(string Id)
        {
            if (Id.Length == 18)
            {
                bool check = CheckIDCard18(Id);
                return check;
            }
            else if (Id.Length == 15)
            {
                bool check = CheckIDCard15(Id);
                return check;
            }
            else
            {
                return false;
            }
        }

        public static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }

        public static bool CheckIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }

        #endregion        


        /// <summary>
        /// 隐藏单选按钮焦点框
        /// </summary>
        /// <param name="control">radiobutton</param>
        public static void HideFocusCues(object obj)
        {
            try
            {
                Control control = (Control)obj;
                Type vType = typeof(Control);
                FieldInfo vFieldInfo = vType.GetField("uiCuesState",
                    BindingFlags.Instance | BindingFlags.Public |
                    BindingFlags.NonPublic | BindingFlags.Static |
                    BindingFlags.FlattenHierarchy);
                vFieldInfo.SetValue(control, 15);
            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }

            
        }

       /// <summary>
        ///  為panel畫邊 確定必須是panel border 邊寬度
       /// </summary>
       /// <param name="a">三原色</param>
       /// <param name="b"></param>
       /// <param name="c"></param>
       /// <param name="border">邊粗</param>
       /// <param name="e"></param>
       /// <param name="sender"></param>
       /// <param name="style">邊樣式</param>
        public static void DrawPanelBorder(int a,int b,int c,int border,PaintEventArgs e,object sender)
        {
            try
            {
                ControlPaint.DrawBorder
                    (
                        e.Graphics,
                        (sender as Panel).ClientRectangle,
                        Color.FromArgb(((int)(((byte)(a)))), ((int)(((byte)(b)))), ((int)(((byte)(c))))),border,ButtonBorderStyle.Solid,
                        Color.FromArgb(((int)(((byte)(a)))), ((int)(((byte)(b)))), ((int)(((byte)(c))))),border,ButtonBorderStyle.Solid, 
                        Color.FromArgb(((int)(((byte)(a)))), ((int)(((byte)(b)))), ((int)(((byte)(c))))),border,ButtonBorderStyle.Solid,
                        Color.FromArgb(((int)(((byte)(a)))), ((int)(((byte)(b)))), ((int)(((byte)(c))))),border,ButtonBorderStyle.Solid
                    );
            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }
        }

        public static void DrawPanelBorder(Color color, int border, PaintEventArgs e, object sender)
        {
            try
            {
                ControlPaint.DrawBorder
                    (
                        e.Graphics,
                        (sender as Panel).ClientRectangle,
                        color, border, ButtonBorderStyle.Solid,
                        color, border, ButtonBorderStyle.Solid,
                        color, border, ButtonBorderStyle.Solid,
                        color, border, ButtonBorderStyle.Solid
                    );
            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }


        }

        /// <summary>
        /// 评级转换描述
        /// </summary>
        /// <param name="str">0,★+文字，1仅★</param>
        /// <returns></returns>
        public static string PingjiChange1(string str)
        {
            if (str == "1")
                str = "★卖出";
            else if (str == "2")
                str = "★★减持";
            else if (str == "3")
                str = "★★★谨慎持有";
            else if (str == "4")
                str = "★★★★持有";
            else if (str == "5")
                str = "★★★★★增持";
            else
                str = "--";
            return str;
        }

        /// <summary>
        /// ★
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string retrunValues(string str)
        {
            string returnStr = "";
            try
            {
                if (str == "" || str == null || str == "0")
                    returnStr = "--";
                else
                {
                    for (int i = 0; i < int.Parse(str); i++)
                    {
                        returnStr += "★";
                    }
                }
            }
            catch
            {
                returnStr = "--";
            }
            return returnStr;
        }


        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="sererPath">服务器下载目录</param>
        /// <param name="LocaPath">本地保存目录</param>
        /// <param name="filename">文件名</param>
        public static void DownLoadFile(string sererPath, string LocaPath, string filename)
        {
            try
            {
                //string sererPath = "http://192.168.50.5:7003/PortfolioFile/";
                //文件存在删除
                if (File.Exists(LocaPath + filename))
                {
                    return;
                   // File.Delete(LocaPath + filename);
                }

                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sererPath + filename);

                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(LocaPath + filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);

                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }
        }

        /// <summary>
        /// 下载文件 每次都下载文件 每次覆盖
        /// </summary>
        /// <param name="sererPath">服务器下载目录</param>
        /// <param name="LocaPath">本地保存目录</param>
        /// <param name="filename">文件名</param>
        public static void DownLoadFile(string sererPath, string LocaPath, string filename,bool boo)
        {
            try
            {
                

                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sererPath + filename);

                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(LocaPath + filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);

                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception ex)
            {
                //config.Debug(ex.ToString(), config.debugType.error);需要调用通用写日志方法
            }
        }


        #endregion


        /// <summary>
        /// 这个方法返回两个日期相差多少年，多少月，多少日
        /// </summary>
        /// <param name="dteStartTime">起始日期</param>
        /// <param name="dteOverTime">结束日期</param>
        /// <param name="sFlg">y年，m月,d天</param>
        /// <returns>参数对应的值</returns>
        public double dateDiff(DateTime dteStartTime, DateTime dteOverTime, string sFlg)
        {
            double dJianGe = 0;
            double dYearLen;
            double dMonthLen;
            System.TimeSpan objT;

            dMonthLen = (365 / 12);

            objT = dteOverTime.Subtract(dteStartTime);
            dYearLen = 365;
            switch (sFlg)
            {
                case "y":
                    {
                        dJianGe = System.Convert.ToInt32(objT.Days / dYearLen);
                        break;
                    }
                case "m":
                    {
                        dJianGe = System.Convert.ToInt32(objT.Days / dMonthLen);
                        break;
                    }
                case "d":
                    {
                        dJianGe = objT.TotalDays;
                        break;
                    }
            }
            return dJianGe;
        }
    }
}
